//
//  FZUserAccountViewModel.swift
//  FZSina_Swift
//
//  Created by 李忠 on 7/22/16.
//  Copyright © 2016 FZLZ. All rights reserved.
//

import UIKit

class FZUserAccountViewModel: NSObject {
    
    //MAKR: 单利实现
    static let sharedUserAcount: FZUserAccountViewModel = FZUserAccountViewModel()
    //定义是否请求成功 闭包
    typealias SuccessCallBack = (isSucc: Bool)->()
    //用户账号
    var userAccount: FZUserAccountModel?
    
    //Access_Token 数据
    var Access_Token: String? {
        get{
            guard let userA = userAccount else{
                return nil
            }
            guard let access = userA.access_token else{
                return nil
            }
            
            let oldDate = userA.expires_date!
            if oldDate.compare(CURRENTDATE) == NSComparisonResult.OrderedDescending {
                return access
            }

            return nil
        }
    }
    
    
    //是否登录的属性
    var isLogin: Bool {
        
        get{
            
            return Access_Token != nil
        }
    }
    
    
    /// 数据存放地址
    let filePath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archiver")
    
    //MARK: 初始化方法
    override init() {
        super.init()
        userAccount = getUserAcount()
    }
    
    
}

//MARK:==========================读/存==========================

extension FZUserAccountViewModel{
    
    //读取
    private func getUserAcount() -> FZUserAccountModel? {
        
        return (NSKeyedUnarchiver.unarchiveObjectWithFile(filePath)  as? FZUserAccountModel)
        
    }
    
    //保存
    private func saveUserAcount(userAcount: FZUserAccountModel){
        
        //在保存的时候给userAccount赋值
        self.userAccount = userAcount
        //归档
        NSKeyedArchiver.archiveRootObject(userAcount, toFile: filePath)
        
    }
    
}

//MARK:==========================加载用户信息==========================
extension FZUserAccountViewModel{
    //得到用户access_token
    func loadUserAccount(code: String, isSuccess: SuccessCallBack) {
        FZNetworking.sharedTools.oauthLoadUserAccount(code) { (responseObject, error) in
            if error != nil{
                print("求情accessToken的网络请求出错： \(error)")
                isSuccess(isSucc: false)
                return
            }
            //使用guard 做拦截防止responseObject为空
            guard let response = responseObject else{
                isSuccess(isSucc: false)
                return
            }
            let userAccount = FZUserAccountModel(dic: response as! [String : AnyObject])
            
            //请求用户信息
            self.loadUserAccountInfo(userAccount, isSuccess: isSuccess)
        }
    }
    
    //加载用户信息
    private func loadUserAccountInfo(userAccount: FZUserAccountModel, isSuccess: SuccessCallBack) {
        
        FZNetworking.sharedTools.oauthLoadUserAcccountInfo(userAccount) { (responseObject, error) in
            
            if error != nil{
                print("求情accessToken的网络请求出错： \(error)")
                isSuccess(isSucc: false)
                return
            }
            
            //使用guard 做拦截防止responseObject为空
            guard let response = responseObject else{
                isSuccess(isSucc: false)
                return
            }
            
            let res = response as! [String : AnyObject]
            userAccount.screen_name = res["screen_name"] as? String
            userAccount.avatar_large = res["avatar_large"] as? String
            
            //MARK: 归档数据
            self.saveUserAcount(userAccount)
            isSuccess(isSucc: true)
        }
        
    }
    
}
